﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Compression;
using System.IO;
using BellAssistant.Common.CommonHelper;

namespace BellAssistant
{
    public partial class FrmBase : XtraForm
    {
        /// <summary>
        /// 用于记录日志(用法: logger.Error(); logger.Debug(); logger.Info();)
        /// </summary>
        //public ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static string RoamingPath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.CompanyName), Application.ProductName); //C:\Users\****\AppData\Roaming\XZHKJ\SSCMS\
        private static string iniFilePath = Path.Combine(RoamingPath, "bell.pdb");
        public INIFileHelper iniFile = null;

        public FrmBase()
        {
            InitializeComponent();
            this.FormClosed += new FormClosedEventHandler(FrmBase_FormClosed);
            iniFile = new INIFileHelper(iniFilePath);
        }

        void FrmBase_FormClosed(object sender, FormClosedEventArgs e)
        {
            GC.Collect();
        }

        /// <summary>
        /// 弹出空白图标对话框
        /// </summary>
        /// <param name="message"></param>
        public void ShowNoneMsgBox(string message)
        {
            MessageBox.Show(message, Msg.Infor, MessageBoxButtons.OK, MessageBoxIcon.None);
        }

        /// <summary>
        /// 弹出信息图标对话框
        /// </summary>
        /// <param name="message"></param>
        public void ShowInfoMsgBox(string message)
        {
            MessageBox.Show(message, Msg.Infor, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 弹出警告图标对话框
        /// </summary>
        /// <param name="message"></param>
        public void ShowWarningMsgBox(string message)
        {
            MessageBox.Show(message, Msg.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        /// <summary>
        /// 弹出错误图标对话框
        /// </summary>
        /// <param name="message"></param>
        public void ShowErrorMsgBox(string message)
        {
            MessageBox.Show(message, Msg.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        /// <summary>
        /// 弹出询问图标对话框
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <param name="showYesNoButton">对话框默认显示'确定-取消'，否则显示'是-否'</param>
        /// <param name="showWarningTitle">对话框标题默认显示'提示'，否则显示'警告'</param>
        public DialogResult ShowQuestionMsgBox(string message, bool showYesNoButton = false, bool showWarningTitle = false)
        {
            DialogResult dr;
            if (showYesNoButton)
            {
                if (showWarningTitle)
                    dr = MessageBox.Show(message, Msg.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                else
                    dr = MessageBox.Show(message, Msg.Infor, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
            else
            {
                if (showWarningTitle)
                    dr = MessageBox.Show(message, Msg.Warning, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                else
                    dr = MessageBox.Show(message, Msg.Infor, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            }
            return dr;
        }

        /// <summary>
        /// 记录系统异常信息到日志
        /// </summary>
        /// <param name="message"></param>
        public void RecordErrorMsg(string message)
        {
            RecordLogs(message);
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="message"></param>
        private void RecordLogs(string message)
        {
            string logFilePath = Path.Combine(Application.StartupPath, "Logs");
            string logName = DateTime.Now.ToString("yyyyMMdd") + ".log";
            string fileName = Path.Combine(logFilePath, logName);
            DirectoryInfo dic = new DirectoryInfo(logFilePath);
            if (!dic.Exists)
            {
                dic.Create();
            }

            System.IO.FileInfo file = new System.IO.FileInfo(fileName);
            if (!file.Exists)
            {
                using (FileStream fs = file.Create())
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
            else
            {
                using (StreamWriter sw = new StreamWriter(fileName, true, Encoding.Default))
                {
                    StringBuilder log = new StringBuilder(Environment.NewLine);
                    log.AppendFormat("异常时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    if (LoginInfo.CurrentUser != null)
                    {
                        log.Append(Environment.NewLine);
                        log.AppendFormat("登录帐号：{0}，\t姓名：{1}", LoginInfo.CurrentUser.LoginName, LoginInfo.CurrentUser.UserName);
                    }
                    log.Append(Environment.NewLine);
                    log.AppendFormat("异常信息：{0}", message);

                    sw.Flush();
                    sw.Write(log);
                    sw.Close();
                }
            }
        }

        /// <summary>
        /// 接口地址
        /// </summary>
        //public string ApiUrl
        //{
        //    get
        //    {
        //        string apiUrl = ConfigurationManager.AppSettings["APIUrl"];
        //        return apiUrl;
        //    }
        //}

        /// <summary>
        /// 接口地址
        /// </summary>
        //public string CardApiUrl
        //{
        //    get
        //    {
        //        string cardApiUrl = ConfigurationManager.AppSettings["CardAPIUrl"];
        //        return cardApiUrl;
        //    }
        //}

        private byte[] Compression(byte[] data, CompressionMode mode)
        {
            DeflateStream zip = null;
            try
            {
                if (mode == CompressionMode.Compress)
                {
                    MemoryStream ms = new MemoryStream();
                    zip = new DeflateStream(ms, mode, true);
                    zip.Write(data, 0, data.Length);
                    zip.Close();
                    return ms.ToArray();
                }
                else
                {
                    MemoryStream ms = new MemoryStream();
                    ms.Write(data, 0, data.Length);
                    ms.Flush();
                    ms.Position = 0;
                    zip = new DeflateStream(ms, mode, true);
                    MemoryStream os = new MemoryStream();
                    int SIZE = 1024;
                    byte[] buf = new byte[SIZE];
                    int l = 0;
                    do
                    {
                        l = zip.Read(buf, 0, SIZE);
                        if (l == 0) l = zip.Read(buf, 0, SIZE);
                        os.Write(buf, 0, l);
                    } while (l != 0);
                    zip.Close();
                    return os.ToArray();
                }
            }
            catch
            {
                if (zip != null) zip.Close();
                return null;
            }
            finally
            {
                if (zip != null) zip.Close();
            }
        }
    }
}